<?php

namespace app\home\controller\user;

//引入公共控制器
use app\common\controller\Home;
//引入Cookie
use think\Cookie;

class Subject extends Home
{

  // 不需要登陆的方法
  // protected $noNeedLogin = ['details'];

    public function __construct()
  {
    //继承父类
    parent::__construct();
      //加载模型
      $this->BusinessModel = model('Business.Business');
      $this->RecordModel = model('Business.Record');
      $this->SubjectModel = model('Subject.Subject');
      $this->CommentModel = model('Subject.Comment');
      $this->ChapterModel = model('Subject.Chapter');
      $this->OrderModel = model('Subject.Order');
  }

    public function order()
    {
       // 查询数据
    $business = $this->BusinessModel->find($this->auth->id);

    $id = isset($this->auth['id']) ? $this->auth['id'] : 0 ;

    $operation = $this->OrderModel->alias('c')->join('subject p', 'c.subid = p.id')->where(['busid' => $business['id']])->select();

    $Recordlist = $this->RecordModel->where(['busid' => $id])->select();     

    $order = $this->OrderModel->alias('c')->join('subject p', 'c.subid = p.id')->where(['busid' => $business['id']])->select();

    $Orderlist = $this->OrderModel->with('subject')->where('busid', $id)-> select();

    foreach($Orderlist as $item){
        // 查询当前用户购买的所有课程是否有评论
        $comment = $this->CommentModel->where(['subid' => $item['subid'], 'busid' => $item['busid']])->find();
        if($comment){
            $item['commentstate'] = true;
        } else {
            $item['commentstate'] = false;
        }
    }

    $this->assign([
      'Recordlist' => $Recordlist,
      'business' => $business,
      'order' => $order,
      'operation'=>$operation,
      'Orderlist' => $Orderlist,
    ]);
      return $this->view->fetch();
    }

    public function contact()
    {
      $lunbo1 = $this->SubjectModel->order("createtime", 'desc')->paginate(3);
        $lunbo = $this->SubjectModel->find();
        $SubjectList = $this->SubjectModel->orderRaw("LPAD(LOWER(likes), 10,0) DESC")->limit(6)->select();
        $this->assign([
          'lunbo1'=>$lunbo1,
          'lunbo'=>$lunbo,
          'SubjectList' => $SubjectList,
        ]);
      return $this->view->fetch();
    }

   
    public function comment ()
    {
      
      $list = $this->ChapterModel ->select();
     
      $cid = $this->request->param('cid', 0, 'trim');

      $content = $this->request->param('content', '', 'trim');

      $id = isset($this->auth['id']) ? $this->auth['id'] : 0 ;

      $subject = $this->SubjectModel->find($cid);

     

      $this->assign([
        'list'=>$list,
        'subject' =>$subject,
      
      ]);

      // var_dump($list);
      // exit;

   
      if($this->request->isPost())
      {
      $params = $this->request->param();

      $id = $this->auth['id'];

      $cid = $this->request->param('cid');

      // var_dump($list);
      // exit;
      $data=[
        'content' => $params['content'],
        'busid' => $id,
        'listid' => $list,
        'subid' => $cid,
        // 'listid' => $params['list'],
      ];
      
    
      // echo $this->auth['id'];
      // exit;
     
      $result = $this->CommentModel->validate('common/Business/Comment')->save($data);

     

      $this->success('评论成功', url('/home/user/subject/details',['cid' => $subject['id']]));

    }
   
 

      return $this->view->fetch();
    }

    public function playing ()
    {


      $cid = $this->request->param('cid');

      $id = $this->request->param('id',0);

      $Chapterlist = $this->ChapterModel->with('subject')->select();

    //  var_dump($Chapterlist );
    //   exit;

    if($id)
    {
      $items = $this->ChapterModel->find($id);
    }else{
      $items =  $Chapterlist[0];
    }

      $video = $this->ChapterModel ->alias('c')->join('subject s', 'c.subid = s.id')->where('subid',$cid)->find();

      //  var_dump($video );
      // exit;

      $this->assign([
        'Chapterlist'=>$Chapterlist,
        'video'=>$video,
        'items' => $items,
        'cid' => $cid
      ]);

      return $this->view->fetch();
    }

    public function commentok ()
    {
      return $this->view->fetch();
    }  

 // 购买完成的页面
 public function buycomplete()
 {
  $subject = $this->SubjectModel->find();
  $cid = $this->request->param('cid');

    //  var_dump($cid);
    //  exit;

     $this->assign('cid', $cid);
     return $this->view->fetch();
 }

    public function details()
    {
      $subid = $this->request->param('subid', 0);

      $subject = $this->SubjectModel->find();

    $cid = $this->request->param('cid');

    $chapterlist = $this->SubjectModel ->alias('c')->join('subject_list s', 's.subid = c.id')->where('subid',$cid)->select();
    // $chapterlist = $this->ChapterModel->where('subid', $subid)->select();

    // halt($chapterlist);

    $bus = $this->auth->id;
    $order =  $this->OrderModel->alias('o')->join('subject s', 'o.subid = s.id')->where('subid',$cid)->value('busid');

    if($order == $bus){
    $ol = true;
    // echo $ol;
    // exit;
    }else{
      $ol = false;
      
    }

   

    $operation = $this->SubjectModel->find($cid);
    
    $course = $this->ChapterModel->where('subid',$cid)->column('id');

    // halt($order);
    $commentlist = $this->CommentModel->alias('c')->join('business p', 'c.busid = p.id')->whereIn('subid',$cid)->paginate(5);
    // $commentlist = $this->CommentModel->alias('c')->join('business p', 'c.busid = p.id')->whereIn('subid',$cid)->select();
    
    $this->assign([
      'operation'=>$operation,
      'commentlist'=>$commentlist,
      'chapterlist' => $chapterlist,
      'subject'=>$subject,
      'cid' => $cid,
      'ol'=>$ol,
    ]);
    
      return $this->view->fetch();
    }
  
    //点赞功能
    public function likes()
    {

      //Thinkphp 判断是否为ajax的请求
      if($this->request->isAjax())
      {
        
      //  echo 22222;
       //获取cookie赋值
       $this->auth = cookie('auth') ? cookie('auth') : [];

       $busid = isset($this->auth['id']) ? $this->auth['id'] : 0;
       $business = $this->BusinessModel->find($busid);
       

       //接收课程id
       $subject = $this->SubjectModel->find();
        $subid = $this->request->param('subid',0);

      //根据id查询课程是否存在
        $subject = $this->SubjectModel->find($subid);
        // var_dump($subject->toArray());
        // exit;

        // var_dump($business['id']);
        // var_dump($subject['likes']);
       
        //字符串变数组
        // $subject['likes'] = null;
        $likes = explode(',',$subject['likes']);

        // 数组要去除空元素
        $likes = array_filter($likes);

        //取消点赞，如果不在就增加点赞
        if (in_array($busid, $likes)) {
          // array_search() 函数可以在数组中搜索指定键值，并返回对应的键名（下标）。
          $key = array_search($busid, $likes);
          unset($likes[$key]);

          // $like = is_array($likes) ? implode(',', $likes) : '';
          //组装数据准备更新
          $data = [
              'id' => $subid,
              'likes' => implode(',' , $likes) //从数组变回字符串
          ];
          $result = $this->SubjectModel->isUpdate()->save($data);
          if ($result) {
              $this->success('取消点赞成功');
          } else {
              $this->error('取消点赞失败');
          }
      } else {
          $likes[] = $busid;
          // 给数组添加元素
          //    array_push($likes, $id);
          // $like = is_array($likes) ? implode(',', $likes) : '';
          $data = [
              'id' => $subid,
              'likes' => implode(',' , $likes) 
          ];
          $result = $this->SubjectModel->isUpdate()->save($data);
          if ($result) {
              $this->success('点赞成功');
          } else {
              $this->error('点赞失败');
          }
      }
    }
    }

   // 播放视频
   public function play()
   {
       // 章节ID
       $listid = $this->request->param('listid', 0, 'trim');
       // 课程ID
       $subid = $this->request->param('subid', 0, 'trim');

       // 用户ID
       $id = $this->auth['id'] ? $this->auth['id'] : 0;

       $userinfo = $this->BusinessModel->find($id);

       if (!$userinfo) {
           $this->error('当前用户不存在');
       }

       $coures =  $this->SubjectModel->find($subid);

       if (!$coures) {
           $this->error('当课程不存在');
       }
       // 判断当前用户是否有购买过课程
       $orderinfo =  $this->OrderModel->where(['subid' => $subid, 'busid' => $id])->find();

       if ($orderinfo) {
           // 当前用户是否点击课程章节播放视频
           if ($listid > 0) {
               $result = $this->ChapterModel->find($listid);

               $this->success('章节详情', '', $result);
           } else {
               $result = $this->ChapterModel->where('subid', $subid)->find();

               $this->success('章节详情', '', $result);
           }
       } else {
           $this->error('请先去购买课程再播放', '', 'buy');
       }
   }

    //购买课程
    public function buy()
    {

      // var_dump(11111);
      //   exit;
      
        //获取当前购买的课程id
        $subid = $this->request->param('subid', 0);

        // var_dump($subid);
        // exit;

        $busid = $this->auth['id'];

        //根据id去查询课程是否存在
        $subject = $this->SubjectModel->find($subid);

        // var_dump($subject);
        // exit;

        if (!$subject) {
          $this->error('当课程不存在');
          exit;
      }

    $where = [
      'subid' => $subid,
      'busid' => $busid
    ];

    //判断是否已经购买过
  //   $order = $this->OrderModel->where([''])->find();

  //   if ($order) {
  //     $this->error('该课程已经购买过了，无须重复购买');
  //     exit;
  // }

  //余额购买

  //课程价格
  $price = isset($subject['price']) ? trim($subject['price']) : 0;

  //个人余额
  $money = isset($this->auth['money']) ?  trim($this->auth['money']) : 0;

  //个人余额 - 课程价格
  $Updatemoney = bcsub($money, $price);

  if ($Updatemoney < 0) {
      $this->error('余额不足，请去充值');
  }
    // echo '余额购买 ';
    // exit;
  //}

    //开启操作表的事务
     // 课程订单表
     $this->OrderModel->startTrans();
     // 用户
     $this->BusinessModel->startTrans();
     // 消费记录
     $this->RecordModel->startTrans();

     //生成订单号
     $code = build_code("SUB");

    //  var_dump($code);
    //  exit;

     $OrderData = [
      'subid' => $subid,
      'busid' => $busid,
      'total' => $price,
      'code' => $code,
  ];

  //插入订单表
  $OrderStatus = $this->OrderModel->validate('common/Subject/Order')->save($OrderData);

  //订单插入失败
  if ($OrderStatus === FALSE) {
    $this->error($this->Order->getError());
    exit;
}

  //更新用户表
  $BusData = [
    'id' => $busid,
    'money' => $Updatemoney
  ];

  //判断成交状态，如果未成交改成已成交
  if(!$this->auth['deal']){
    $BusData['deal'] = 1;
  }

  //更新
  $BusStatus = $this->BusinessModel->isUpdate()->save($BusData);

  if($BusStatus === FALSE)
  {
    //订单回滚
    $this->OrderModel->rollback();
    $this->error($this->BusinessModel->getError());
    exit;
  }

  //插入消费记录表
  $subtitle = $subject['title'];
  $RecordData = [
    'total' => $price,
    'busid' => $busid,
    'content' => "购买了[{$subtitle}]课程,花费了￥{$price}元",
];

  $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

  if ($RecordStatus === FALSE) {
    $this->BusinessModel->rollback();
    $this->OrderModel->rollback();
    $this->error($this->RecordModel->getError());
    exit;
}

  if($OrderStatus === FALSE || $BusStatus === FALSE || $RecordStatus === FALSE){
    $this->RecordModel->rollback();
    $this->BusinessModel->rollback();
    $this->OrderModel->rollback();
    $this->error('购买失败');
    exit;
  }else 
  {
    //3个步骤都成功，3个模拟的步骤都要提交事务 真正执行到数据库中
    $this->OrderModel->commit();
    $this->BusinessModel->commit();
    $this->RecordModel->commit();
    $this->success('购买成功');
    exit;
}

  
    
}
}